package com.lemon.common.context;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * Session 上下文环境
 * 用一个 hashmap 保存所有的 session 对象，hashmap 的 key 就是 sessionId
 * 这样能从 cookie 中获取 sessionId，进而获取到 session
 *
 * @author ymh
 * @date 2019-04-06 08:55
 */
public class SessionContext {

    private static SessionContext instance;
    private HashMap<String, HttpSession> sessionMap;

    private SessionContext() {
        sessionMap = new HashMap<>();
    }

    public static SessionContext getInstance() {
        if (instance == null) {
            instance = new SessionContext();
        }
        return instance;
    }

    public synchronized void addSession(HttpSession session) {
        if (session != null) {
            sessionMap.put(session.getId(), session);
        }
    }

    public synchronized void delSession(HttpSession session) {
        if (session != null) {
            sessionMap.remove(session.getId());
        }
    }

    public synchronized HttpSession getSession(String sessionID) {
        if (sessionID == null) {
            return null;
        }
        return sessionMap.get(sessionID);
    }
}
